/**
 * 混合数据模式 API 测试脚本
 * 用于测试混合数据模式下的API调用是否能正常工作
 * 运行方法：node test_hybrid_api.js
 */

// 导入必需的模块
import { hybridRequest } from './hybridApi.js';
import './mockDataAdditions.js'; // 确保加载额外的模拟数据

// 配置测试环境
const testConfig = {
  // 是否在控制台打印详细信息
  verbose: true,
  // 是否使用颜色输出（在支持的终端中）
  useColors: true
};

// 打印彩色文本的辅助函数
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  dim: '\x1b[2m',
  underscore: '\x1b[4m',
  blink: '\x1b[5m',
  reverse: '\x1b[7m',
  hidden: '\x1b[8m',
  
  fg: {
    black: '\x1b[30m',
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    magenta: '\x1b[35m',
    cyan: '\x1b[36m',
    white: '\x1b[37m',
    crimson: '\x1b[38m'
  },
  
  bg: {
    black: '\x1b[40m',
    red: '\x1b[41m',
    green: '\x1b[42m',
    yellow: '\x1b[43m',
    blue: '\x1b[44m',
    magenta: '\x1b[45m',
    cyan: '\x1b[46m',
    white: '\x1b[47m',
    crimson: '\x1b[48m'
  }
};

// 彩色日志函数
const colorLog = {
  info: (msg) => console.log(`${testConfig.useColors ? colors.fg.cyan : ''}[INFO]${testConfig.useColors ? colors.reset : ''} ${msg}`),
  success: (msg) => console.log(`${testConfig.useColors ? colors.fg.green : ''}[SUCCESS]${testConfig.useColors ? colors.reset : ''} ${msg}`),
  warn: (msg) => console.log(`${testConfig.useColors ? colors.fg.yellow : ''}[WARNING]${testConfig.useColors ? colors.reset : ''} ${msg}`),
  error: (msg) => console.log(`${testConfig.useColors ? colors.fg.red : ''}[ERROR]${testConfig.useColors ? colors.reset : ''} ${msg}`),
  debug: (msg) => testConfig.verbose && console.log(`${testConfig.useColors ? colors.fg.magenta : ''}[DEBUG]${testConfig.useColors ? colors.reset : ''} ${msg}`),
};

/**
 * 测试特定API路径
 * @param {string} path - API路径
 * @param {object} options - 请求选项
 * @returns {Promise<object>} 测试结果
 */
async function testApiPath(path, options = {}) {
  colorLog.info(`测试API路径: ${path}`);
  
  try {
    const startTime = Date.now();
    const response = await hybridRequest(path, options);
    const endTime = Date.now();
    
    colorLog.success(`成功获取数据 (${endTime - startTime}ms)`);
    colorLog.debug(`响应数据: ${JSON.stringify(response).substring(0, 200)}...`);
    
    return {
      path,
      success: true,
      responseTime: endTime - startTime,
      data: response
    };
  } catch (error) {
    colorLog.error(`请求失败: ${error.message}`);
    return {
      path,
      success: false,
      error: error.message
    };
  }
}

/**
 * 运行所有API测试
 */
async function runTests() {
  colorLog.info('开始测试混合数据API...');
  
  const testResults = {
    total: 0,
    success: 0,
    failed: 0,
    results: []
  };
  
  // 测试仪表盘概览
  const testPaths = [
    '/dashboard/overview',
    '/dashboard/stats',
    '/dashboard/alerts',
    '/dashboard/device-status'
  ];
  
  colorLog.info(`将测试 ${testPaths.length} 个API端点`);
  
  for (const path of testPaths) {
    testResults.total++;
    const result = await testApiPath(path);
    
    if (result.success) {
      testResults.success++;
    } else {
      testResults.failed++;
    }
    
    testResults.results.push(result);
    
    // 在测试之间添加短暂延迟
    await new Promise(resolve => setTimeout(resolve, 500));
  }
  
  // 打印测试摘要
  console.log('\n' + '-'.repeat(50));
  colorLog.info('测试完成!');
  console.log('-'.repeat(50));
  colorLog.info(`总共: ${testResults.total} 测试`);
  colorLog.success(`成功: ${testResults.success} 测试`);
  
  if (testResults.failed > 0) {
    colorLog.error(`失败: ${testResults.failed} 测试`);
  } else {
    colorLog.success('全部测试通过!');
  }
  
  console.log('-'.repeat(50) + '\n');
  
  return testResults;
}

// 执行测试
runTests().then((results) => {
  if (results.failed > 0) {
    process.exit(1); // 如果有失败的测试，退出代码为1
  }
}).catch((error) => {
  colorLog.error(`运行测试时出错: ${error.message}`);
  process.exit(1);
});
